package com.inonworks.mw.log;




import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
@Slf4j
public class AroundLogInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Method method = methodInvocation.getMethod();
        AroundLog aroundLog = getAnnotation(method);
        if(aroundLog == null){
            return methodInvocation.proceed();
        }
        long startTime = System.currentTimeMillis();
        try {
            log.info("["+aroundLog.value()+"] 开始执行");
            Object proceed = methodInvocation.proceed();
            log.info("["+aroundLog.value()+"] 执行结束");
            return proceed;
        } catch (Throwable throwable){
            log.warn("["+aroundLog.value()+"] 执行异常",throwable);
            throw throwable;
        } finally {
            long endTime = System.currentTimeMillis();
            log.info("["+aroundLog.value()+"] 共消耗 [{}ms]", endTime-startTime);
        }
    }

    private AroundLog getAnnotation(Method method) {
        if(method.isAnnotationPresent(AroundLog.class)) {
            return method.getAnnotation(AroundLog.class);
        }
        return null;
    }
}
